package com.cf.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cf.domain.dto.UserDTO;
import com.cf.domain.pojo.PageQuery;
import com.cf.domain.pojo.Team;
import com.cf.domain.pojo.User;
import com.cf.domain.vo.TeamVO;
import com.cf.domain.vo.UserVO;
import com.cf.enums.UserRole;
import com.cf.exception.MyException;
import com.cf.mapper.UserMapper;
import com.cf.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;
    @Override
    public UserVO login(UserDTO userDTO) {
        //获取接口传递的用户名与密码
        String phone = userDTO.getPhone();
        String password = userDTO.getPassword();
        //根据用户名与密码查询用户信息
        User user = lambdaQuery().eq(User::getPhone, phone).one();
        if(user==null){
            throw new MyException("用户名错误");
        }
//        Assert.notNull(user, "用户名错误");

        //校验用户状态，看是否冻结状态
        if(user.getLocked()==1){
            throw new MyException("该用户账户已被冻结！");
        }

        //校验密码是否正确
        if(!SecureUtil.md5(password).equals(user.getPassword())){
            throw new MyException("密码错误！");
        }
        /* 获取token并传递给前端进行存储 */
        return getUserVO(user);
    }

    private UserVO getUserVO(User user) {
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setName(user.getName());
        userVO.setPhone(user.getPhone());
        userVO.setEmail(user.getEmail());
        userVO.setArea(user.getArea());
        userVO.setType(user.getType());
        userVO.setUserRole(user.getUserRole());
        return userVO;
    }

    @Override
    public UserVO register(UserDTO userDTO) {
        //查询数据库是否存在该用户
        User user = lambdaQuery().eq(User::getPhone, userDTO.getPhone()).eq(User::getLocked, 0).one();
        if(user!=null){
            throw new MyException("该用户名已经存在！");
        }
//        Assert.isNull(user, "该用户名已经存在");
        user = new User();
        user.setName(userDTO.getName());
        user.setEmail(userDTO.getEmail());
        user.setPhone(userDTO.getPhone());
        //对password进行加密并赋值给User对象
        user.setPassword(SecureUtil.md5(userDTO.getPassword()));
        user.setArea(userDTO.getArea());
        user.setUserRole(userDTO.getUserRole());
        user.setType(userDTO.getType());
        user.setSource(userDTO.getSource());
        //保存用户信息到数据库
        save(user);

        return getUserVO(user);
    }

    @Override
    public int update(UserDTO userDTO) {
        return baseMapper.updateUser(userDTO.getId(), userDTO.getName(), userDTO.getEmail(), userDTO.getArea());
    }

    @Override
    public int updatePwd(UserDTO userDTO, String newPwd) {
        User user = lambdaQuery().eq(User::getId, userDTO.getId()).one();
        if(user == null){
            throw new MyException("请重新登陆！");
        }else{
            if(!user.getPassword().equals(userDTO.getPassword())){
                throw new MyException("原始密码不正确！");
            }
        }
        return baseMapper.updatePwd(userDTO.getId(), SecureUtil.md5(newPwd));
    }

    @Override
    public Page<User> selectList(PageQuery pageQuery) {
        Page<User> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        return userMapper.selectList(page, null);
    }

    @Override
    public Page<TeamVO> selectTeamList(PageQuery pageQuery, UserVO userVO) {
        Page<TeamVO> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        QueryWrapper<TeamVO> wrapper = new QueryWrapper<>();
        wrapper.eq("is_lock", 0);
        if(userVO.getUserRole() == UserRole.ADMIN.getId()){
            wrapper.gt("user_role", 1);
        }
        if(userVO.getUserRole() == UserRole.REGIONADMIN.getId()){
            wrapper.eq("user_role", 3);
        }
        int area = Integer.valueOf((String) pageQuery.getQueryMap().get("areaSearch"));
        if(area > 0){
            wrapper.eq("area", area);
        }
        wrapper.orderByDesc("id");
        return userMapper.selectTeamList(page, wrapper);
    }

    @Override
    public List<TeamVO> selectMembers(Map<String, Object> map, UserVO userVO) {
        QueryWrapper<TeamVO> wrapper = new QueryWrapper<>();
        wrapper.eq("is_lock", 0);
        if(userVO.getUserRole() == UserRole.REGIONADMIN.getId()){
            wrapper.eq("user_role", 3);
        }
        if(userVO.getUserRole() == UserRole.ADMIN.getId()){
            wrapper.gt("user_role", 1);
        }
        int area = Integer.valueOf(map.get("areaSearch").toString());
        if(area > 0){
            wrapper.eq("area", area);
        }
        wrapper.orderByDesc("id");
        return userMapper.selectMembers(wrapper);
    }

    @Override
    public List<TeamVO> selectMembers(Map<String, Object> map) {
        QueryWrapper<TeamVO> wrapper = new QueryWrapper<>();
        wrapper.eq("is_lock", 0).eq("user_role", 3);
        wrapper.notExists("SELECT id FROM t_team_order WHERE t_user.id = t_team_order.user_id");
        wrapper.orderByDesc("id");
        return userMapper.selectMembers(wrapper);
    }

    @Override
    public TeamVO getTeam(Long id) {
        QueryWrapper<TeamVO> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        wrapper.eq("is_lock", 0);
        TeamVO teamVO = userMapper.selectMember(wrapper);
        if(teamVO == null){
            throw new MyException("服务数据出现异常，请刷新重试！");
        }
        return userMapper.selectMember(wrapper);
    }

}
